const Router = require('koa-router')
const jwtToken = require('jsonwebtoken')
const request = require('request')
const mongo = require('../../schedma/db')
const bcrypt = require('bcrypt-nodejs')
const router = new Router()
const secret = 'martinCai'

router.get('/login', async (ctx) => {
  const username = ctx.request.query.username
  const password = ctx.request.query.password
  const userPassword = await mongo.UserSchemal.findOne({username}, {_id: 0, password: 1})
  if (userPassword) {
    const data =  await bcrypt.compareSync(password, userPassword.password)
    if (data) {
      let userToken = {
        name: username
      }
      const token = jwtToken.sign(userToken, secret, {expiresIn: '5h'})
      ctx.body = {
        message: '获取token成功',
        code: 200,
        token
      }
    } else {
      ctx.status = 500
      ctx.body = {
        message: '账号或密码错误',
        code: 500
      }
    }
  } else {
    ctx.status = 500
    ctx.body = {
      message: '账号或密码错误',
      code: 500
    }
  }
})

router.post('/register', async (ctx) => {
  const username = ctx.request.body.username
  const nickname = ctx.request.body.nickname
  const roleId = ctx.request.body.roleId
  const password = await bcrypt.hashSync(ctx.request.body.password)
  const reigster = new mongo.UserSchemal({username, password})
  const userInfo = new mongo.UserInfo({instroce: '', roleId, nickname, username, url: 'http://pes61p15q.bkt.clouddn.com/default.jpg'})
  reigster.save((err) => {
  })
  userInfo.save((err) => {
  })
  ctx.body = {
    message: '注册成功',
    code: 200,
  }
})

router.post('/modeify/password', async (ctx) => {
  const username = ctx.request.body.username
  console.log(username)
  const password = await bcrypt.hashSync(ctx.request.body.password)
  const data = await mongo.UserSchemal.updateOne({username}, {$set: {password}})
  const finds = await mongo.UserInfo.findOne({username: 'martincai'})
  console.log(finds)
  if (data.ok) {
    ctx.body = true
  } else {
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '修改失败'
    }
  }
})

module.exports = router